import 'package:fate_blind_box/network/http_request.dart';
import 'package:fate_blind_box/ui/cooperation/shop_info_upload/shop_info_upload_controller.dart';
import 'package:fate_blind_box/utils/common_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../../../theme/theme_color.dart';
import '../../../utils/bottom_sheet.dart';
import '../../../utils/loading.dart';
import '../../../utils/photo_utils/photo_tool.dart';
import '../../user/institution/companyPodfile.dart';
import '../../user/institution/industry.dart';
import '../address/address_manage_page.dart';
import '../shop_name/shop_name_edit_page.dart';
import '../shop_name/shop_open_time_page.dart';
import '../shop_name/shop_phone_edit_page.dart';
import 'package:dio/dio.dart' as dioFile;

class ShopInfoUploadView extends StatefulWidget {
  const ShopInfoUploadView({Key? key}) : super(key: key);

  @override
  State<ShopInfoUploadView> createState() => _State();
}

class _State extends State<ShopInfoUploadView> {
  ShopInfoUploadController uploadController =
      Get.put(ShopInfoUploadController());

  @override
  Widget build(BuildContext context) {
    return AppWidget.navTitleBar(
      title: '上传商家信息',
      childWidget: Column(
        children: [
          Expanded(
            child: Column(
              children: [
                GetBuilder(
                    id: uploadController.avatarUrlId,
                    builder: (ShopInfoUploadController controller) {
                      return getLeftNameAndArrowView(
                          leftName: '商家头像',
                          rightName:
                              controller.avatarUrl.isEmpty ? '请选择' : '已上传',
                          tapAction: () {
                            PhotoTool.selectPhotoFromSheet(context,
                                callBackUrl: (res) {
                              print('商家头像' + res);
                              controller.avatarUrl = res;
                              controller.update([controller.avatarUrlId]);
                            });
                          });
                    }),
                GetBuilder(
                    id: uploadController.shopNameId,
                    builder: (ShopInfoUploadController controller) {
                      return getLeftNameAndArrowView(
                          leftName: '商家简称',
                          rightName: controller.shopDetailsName.isEmpty
                              ? '请输入'
                              : controller.shopDetailsName,
                          tapAction: () {
                            Get.to(ShopNameEditPage(
                              isFromUpload: true,
                              callBackBlock: (res) {
                                print('商家简称' + res);
                                controller.shopDetailsName = res;
                                controller.update([controller.shopNameId]);
                              },
                            ));
                          });
                    }),
                GetBuilder(
                    id: uploadController.shopIntroduceId,
                    builder: (ShopInfoUploadController controller) {
                      return getLeftNameAndArrowView(
                          leftName: '商家简介',
                          rightName: controller.shopDetailsIntroduce.isEmpty
                              ? '请输入'
                              : controller.shopDetailsIntroduce,
                          tapAction: () {
                            Get.to(CompanyProfileView(
                              isFromUpload: true,
                              callBackBlock: (coverUrl, desStr, detailsUrl) {
                                print('商家详情头像' + coverUrl);
                                print('商家描述' + desStr);
                                print('商家详情图片' + detailsUrl);
                                controller.matchPhoto = coverUrl;
                                controller.shopDetailsIntroduce = desStr;
                                controller.productPhoto = detailsUrl;
                                controller
                                    .update([uploadController.shopIntroduceId]);
                              },
                            ));
                          });
                    }),
                GetBuilder(
                    id: uploadController.mobilPhoneId,
                    builder: (ShopInfoUploadController controller) {
                      return getLeftNameAndArrowView(
                          leftName: '商家电话',
                          rightName: controller.mobilPhone.isEmpty
                              ? '请输入'
                              : controller.mobilPhone,
                          tapAction: () {
                            Get.to(ShopPhoneEditPage(
                              isFromUpload: true,
                              callBlock: (res) {
                                controller.mobilPhone = res;
                                controller.update([controller.mobilPhoneId]);
                                print('商家电话' + res);
                              },
                            ));
                          });
                    }),
                Container(
                  color: ThemeColor.dividerColor,
                  height: 5,
                ),
                GetBuilder(
                    id: uploadController.tradeId,
                    builder: (ShopInfoUploadController controller) {
                      return getLeftNameAndArrowView(
                          leftName: '行业选择',
                          rightName: controller.trade.isEmpty
                              ? '请选择'
                              : controller.trade,
                          tapAction: () {
                            BottomSheetDialog.show(
                                context,
                                IndustryPage(
                                  isFromUpload: true,
                                  callBack: (res) {
                                    controller.trade = res;
                                    print('商家行业' + res);
                                    controller.update([controller.tradeId]);
                                  },
                                ));
                          });
                    }),
                GetBuilder(
                    id: uploadController.openTimeId,
                    builder: (ShopInfoUploadController controller) {
                      String timeStr = controller.shopOpenTime +
                          '-' +
                          controller.shopEndTime;
                      return getLeftNameAndArrowView(
                          leftName: '营业时间',
                          rightName: controller.openTimeStr.isEmpty
                              ? '请选择'
                              : controller.openTimeStr,
                          tapAction: () {
                            Get.to(ShopOpenTimePage(
                              isFromUpload: true,
                              callBlock: (openTime, endTime) {
                                controller.shopOpenTime = openTime;
                                controller.shopEndTime = endTime;
                                controller.openTimeStr =
                                    controller.shopOpenTime +
                                        '-' +
                                        controller.shopEndTime;
                                controller.update([controller.openTimeId]);
                              },
                            ));
                          });
                    }),
                Container(
                  color: ThemeColor.dividerColor,
                  height: 5,
                ),
                GetBuilder(
                    id: uploadController.addressId,
                    builder: (ShopInfoUploadController controller) {
                      return getLeftNameAndArrowView(
                          leftName: '地址',
                          rightName: controller.addressDetails.isEmpty
                              ? '请选择'
                              : controller.addressDetails,
                          tapAction: () {
                            Get.to(AddressManagePage(
                              isFromUpload: true,
                              callBackAddressBlock: (pro, city, area, address,
                                  longitude, latitude) {
                                print('选择地址' + pro);
                                controller.province = pro;
                                controller.city = city;
                                controller.area = area;
                                controller.address = address;
                                controller.longitude = longitude;
                                controller.latitude = latitude;
                                String detailStr = controller.province;
                                if (controller.province == controller.city) {
                                  detailStr =
                                      controller.area + controller.address;
                                } else {
                                  detailStr = controller.city +
                                      controller.area +
                                      controller.address;
                                }
                                controller.addressDetails = detailStr;
                                controller.update([controller.addressId]);
                              },
                            ));
                          });
                    }),
              ],
            ),
          ),
          GestureDetector(
            onTap: () {
              submitInfo();
            },
            child: Container(
              margin: const EdgeInsets.only(left: 20, right: 20, bottom: 20),
              padding: const EdgeInsets.symmetric(vertical: 10),
              alignment: Alignment.center,
              decoration: BoxDecoration(
                  color: ThemeColor.appColor,
                  borderRadius: BorderRadius.circular(5)),
              child: const Text(
                '保存',
                style: TextStyle(color: Colors.white, fontSize: 21),
              ),
            ),
          ),
        ],
      ),
    );
  }

  //提交信息给后台
  void submitInfo() async {
    if (uploadController.avatarUrl.isEmpty) {
      toast('请上传商家头像');
      return;
    }
    if (uploadController.matchPhoto.isEmpty) {
      toast('请上传商家简介图片');
      return;
    }
    if (uploadController.productPhoto.isEmpty) {
      toast('请上传商家详情图片');
      return;
    }
    if (uploadController.shopDetailsName.isEmpty) {
      toast('请完善商家简称');
      return;
    }
    if (uploadController.shopDetailsIntroduce.isEmpty) {
      toast('请完善商家描述');
      return;
    }
    if (uploadController.province.isEmpty) {
      toast('请完善地址');
      return;
    }
    if (uploadController.address.isEmpty) {
      toast('请完善详细地址');
      return;
    }
    if (uploadController.mobilPhone.isEmpty) {
      toast('请完善商家电话');
      return;
    }
    if (uploadController.trade.isEmpty) {
      toast('请选择行业');
      return;
    }
    if (uploadController.shopOpenTime.isEmpty) {
      toast('请完善开始时间');
      return;
    }

    if (uploadController.shopEndTime.isEmpty) {
      toast('请完善结束时间');
      return;
    }

    Map<String, dynamic> datMap = {
      "profilePhoto":
          dioFile.MultipartFile.fromFileSync(uploadController.avatarUrl),
      "matchPhoto":
          dioFile.MultipartFile.fromFileSync(uploadController.matchPhoto),
      "productPhoto":
          dioFile.MultipartFile.fromFileSync(uploadController.productPhoto),
      "shortName": uploadController.shopDetailsName,
      "introduce": uploadController.shopDetailsIntroduce,
      "province": uploadController.province,
      "city": uploadController.city,
      "area": uploadController.area,
      "address": uploadController.address,
      "mobilPhone": uploadController.mobilPhone,
      "trade": uploadController.trade,
      "openTime": uploadController.shopOpenTime,
      "endTime": uploadController.shopEndTime,
      "longitude": uploadController.longitude,
      "latitude": uploadController.latitude,
    };
    var res = await HttpRequest.uploadFile('match-maker/business/addBussiness',
        params: datMap);
    if (res['code'] == 0) {
      final data = res['data'];
      if (data != null) {
        toast('保存成功');
        Get.back();
      } else {
        toast(res['msg']);
      }
    }
  }

  Widget getLeftNameAndArrowView(
      {String leftName = '', Function? tapAction, String rightName = ''}) {
    return GestureDetector(
      onTap: () {
        if (tapAction != null) {
          tapAction();
        }
      },
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 18),
        decoration: BoxDecoration(
            border: Border(
                bottom: BorderSide(color: ThemeColor.dividerColor, width: 1))),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(leftName,
                style: TextStyle(color: ThemeColor.textColor, fontSize: 16)),
            const SizedBox(
              width: 10,
            ),
            Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                Container(
                  constraints: BoxConstraints(maxWidth: 1.sw-14*2-100),
                  child: Text(rightName,
                      maxLines: 1,
                      style: TextStyle(
                          color: ThemeColor.textColorSecond,
                          fontSize: 16,
                          overflow: TextOverflow.ellipsis)),
                ),
                Icon(
                  Icons.arrow_forward_ios,
                  color: ThemeColor.textColorSecond,
                  size: 15,
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
